package m.jclecai.com.adapter.holder;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.ybq.android.spinkit.SpinKitView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.animal.ExpandAnimation;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.dialog.BjdcHHDialog;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.Utils;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/4.
 */

public class BjdcChildHolder extends ViewHolder implements View.OnClickListener {

    @BindView(R.id.tv_failed)
    TextView tvFailed;
    @BindView(R.id.skv)
    SpinKitView skv;
    @BindView(R.id.tv_history_one)
    TextView tvHistoryOne;
    @BindView(R.id.tv_recent_one)
    TextView tvRecentOne;
    @BindView(R.id.tv_recent_two)
    TextView tvRecentTwo;
    @BindView(R.id.tv_rank_one)
    TextView tvRankOne;
    @BindView(R.id.tv_rank_two)
    TextView tvRankTwo;
    @BindView(R.id.tv_ratio_one)
    TextView tvRatioOne;
    @BindView(R.id.tv_ratio_two)
    TextView tvRatioTwo;
    @BindView(R.id.tv_ratio_three)
    TextView tvRatioThree;
    @BindView(R.id.tv_xx)
    TextView tvXx;
    @BindView(R.id.llDetail)
    LinearLayout llDetail;
    @BindView(R.id.ll_ratio)
    LinearLayout ll_ratio;

    //比赛标题容器
    @BindView(R.id.llLeft)
    public LinearLayout llLeft;
    //比赛标题
    @BindView(R.id.item_name)
    public TextView itemName;
    //开赛时间
    @BindView(R.id.item_time)
    public TextView itemTime;
    //左边的队名
    @BindView(R.id.home_team_name)
    public TextView homeTeamName;
    //右边队名
    @BindView(R.id.away_team_name)
    public TextView awayTeamName;
    //标题容器
    @BindView(R.id.ll_match_title)
    public LinearLayout llMatchTitle;
    //比分 半全场
    @BindView(R.id.cb_touzhu)
    public CheckBox cbTouzhu;
    //进球数
    @BindView(R.id.ll_all)
    public LinearLayout llAll;
    //胜平负
    @BindView(R.id.llspf)
    public LinearLayout llspf;
    //胜平负-前面文本
    @BindView(R.id.tv_spf_txt)
    public TextView tv_spf_txt;
    //上下单双
    @BindView(R.id.ll_ds)
    LinearLayout ll_ds;

    @BindView(R.id.iv_detail)
    ImageView iv_detail;
    //记录点击的数据
    Map<String, Map<String, String>> cMap;
    ZqItem mItem;
    int pager = 0;
    int mPosition = 0;
    Callback changed;
    String[] cbf, spf, bqc;
    String[] codes;
    //checkbox高度
    int cH = 0;

    public BjdcChildHolder(Context context, @LayoutRes int resource) {
        super(context, resource);
        cH = ScreenUtil.dip2px(context, 45);
    }

    private void init() {
        init(this.mItem, pager, mPosition);
    }

    public void init(ZqItem item, int pager, int position) {
        if (pager != this.pager) {
            item.setMap(null);
            item.setShowDetail(false);
        }
        cbf = getContext().getResources().getStringArray(
                R.array.jczq_cbf);
        spf = getContext().getResources().getStringArray(
                R.array.jczq_spf);
        bqc = getContext().getResources().getStringArray(
                R.array.jczq_bqc);
        this.mPosition = position;
        this.pager = pager;
        this.mItem = item;
        codes = mItem.getCodes();
        List<String[]> list = FastOk.getList(codes[15], String[].class);
        //左边队名-公共属性
        homeTeamName.setText(codes[3]);
//        homeTeamName.setTextColor(Color.parseColor(codes[17]));
        //右边队名-公共属性
        awayTeamName.setText(codes[4]);
//        awayTeamName.setTextColor(Color.parseColor(codes[17]));
        //联赛名称-公共属性
        itemName.setText(codes[2]);
        //开赛时间-公共属性
        itemTime.setText(codes[7].substring(11, 16) + "截止\n" + codes[1]);
        //隐藏所有的布局
        llspf.setVisibility(GONE);
        llAll.setVisibility(GONE);
        cbTouzhu.setVisibility(GONE);
        ll_ds.setVisibility(GONE);
        llDetail.setAnimation(null);
        llDetail.setVisibility(mItem.isShowDetail() ? VISIBLE : GONE);

        ll_ratio.setVisibility(INVISIBLE);
        skv.setVisibility(INVISIBLE);
        tvFailed.setVisibility(INVISIBLE);
        showRatio(mItem.getRatio());

        iv_detail.setImageResource(mItem.isShowDetail() ? R.drawable.d0 : R.drawable.cz);
        resetCheckBoxStatus(cbTouzhu, "立即投注");

        if (pager == 0) {//胜平负
            llspf.setVisibility(VISIBLE);
            tv_spf_txt.setText(String.valueOf(codes[5]));
            tv_spf_txt.setBackgroundResource(R.color.o);
            if (codes[5].startsWith("+"))
                tv_spf_txt.setBackgroundResource(R.color.font_red);
            else if (codes[5].startsWith("-"))
                tv_spf_txt.setBackgroundResource(R.color.color_0b7e07);
            initSPF(list);
        } else if (pager == 1) {//比分
            cbTouzhu.setVisibility(VISIBLE);
            initBF();
        } else if (pager == 2) {//总进球
            llAll.setVisibility(VISIBLE);
            initZJQ(list);
        } else if (pager == 3) {//半全场
            cbTouzhu.setVisibility(VISIBLE);
            initBQC();
        } else if (pager == 4) {//上下单双
            ll_ds.setVisibility(VISIBLE);
            initDS(list);
        }
    }

    @OnClick(R.id.llLeft)
    void showDetail() {
        iv_detail.setImageResource(!mItem.isShowDetail() ? R.drawable.d0 : R.drawable.cz);
        llDetail.startAnimation(new ExpandAnimation(llDetail, 300, !mItem.isShowDetail()));
        mItem.setShowDetail(!mItem.isShowDetail());
        if(mItem.getRatio() == null) {
            tvFailed.setVisibility(INVISIBLE);
            ll_ratio.setVisibility(INVISIBLE);
            skv.setVisibility(VISIBLE);
            if (this.changed != null)
                this.changed.callback(codes[0], new Callback() {
                    @Override
                    public void callback(JSONObject o) {
                        showRatio(o);
                        mItem.setRatio(o);
                    }

                    @Override
                    public void callbackField() {
                        super.callbackField();
                        tvFailed.setVisibility(VISIBLE);
                        ll_ratio.setVisibility(INVISIBLE);
                        skv.setVisibility(INVISIBLE);
                        //加载失败
                    }
                });
        }else {
            showRatio(mItem.getRatio());
        }
    }

    //显示赛事详情
    void showRatio(JSONObject o){
        if(o == null){
            tvFailed.setVisibility(INVISIBLE);
            skv.setVisibility(VISIBLE);
            ll_ratio.setVisibility(INVISIBLE);
            return;
        }

        tvFailed.setVisibility(INVISIBLE);
        skv.setVisibility(INVISIBLE);
        //加载数据
        ll_ratio.setVisibility(VISIBLE);
        //历史交锋
        JSONArray history = o.getJSONArray("history");
        //平
        int even_count = history.getJSONObject(0).getIntValue("even_count");
        //胜
        int win_count = history.getJSONObject(0).getIntValue("win_count");
        //输
        int lost_count = history.getJSONObject(0).getIntValue("lost_count");
        int history_count = history.getJSONObject(0).getIntValue("history_count");
        String hs = String.format(getResources().getString(R.string.zq_history),
                history_count, codes[3], win_count, even_count, lost_count);
        tvHistoryOne.setText(Html.fromHtml(hs));
        //左边队伍战绩
        JSONArray home_recent = o.getJSONArray("home_recent");
        //平
        int home_even_count = home_recent.getJSONObject(0).getIntValue("even_count");
        //胜
        int home_win_count = home_recent.getJSONObject(0).getIntValue("win_count");
        //输
        int home_lost_count = home_recent.getJSONObject(0).getIntValue("lost_count");
        String hr = getResources().getString(R.string.zq_recent);
        tvRecentOne.setText(String.format(hr, home_win_count, home_even_count, home_lost_count));

        //右边队伍战绩
        JSONArray guest_recent = o.getJSONArray("guest_recent");
        //平
        int guest_even_count = guest_recent.getJSONObject(0).getIntValue("even_count");
        //胜
        int guest_win_count = guest_recent.getJSONObject(0).getIntValue("win_count");
        //输
        int guest_lost_count = guest_recent.getJSONObject(0).getIntValue("lost_count");
        String gr = getResources().getString(R.string.zq_recent);
        tvRecentTwo.setText(String.format(gr, guest_win_count, guest_even_count, guest_lost_count));

        //左边队伍排名
        String home_team_rank = o.getString("home_team_rank");
        tvRankOne.setText(home_team_rank);
        //右边队伍排名
        String guest_team_rank = o.getString("guest_team_rank");
        tvRankTwo.setText(guest_team_rank);
        //投注比例
        JSONArray match_ratio = o.getJSONArray("match_ratio");
        String play_id = match_ratio.getJSONObject(0).getString("PLAY_ID");
        //平
        String enen_ratio = match_ratio.getJSONObject(0).getString("ENEN_RATIO");
        tvRatioTwo.setText(enen_ratio+"%");
        //输
        String lost_ratio = match_ratio.getJSONObject(0).getString("LOST_RATIO");
        tvRatioThree.setText(lost_ratio+"%");
        //胜
        String win_ratio = match_ratio.getJSONObject(0).getString("WIN_RATIO");
        tvRatioOne.setText(win_ratio+"%");
    }

    //其他投注
    @OnClick(R.id.cb_touzhu)
    void cbTouzhu(View v) {
        execCheckParam((CheckBox) v, "立即投注");
    }

    //重置投注按钮状态(CheckBox)
    void resetCheckBoxStatus(final CheckBox cb, final String buttonText) {
        //设置默认选中
        String desc = mItem.getMap() != null && mItem.getMapLength() > 0 ? "已选中" + mItem.getMapLength() + "项" : buttonText;
        cb.setText(desc);
        cb.setChecked(!buttonText.equals(desc));
    }

    /**
     * 处理选中的数据与ui交互
     *
     * @param cb
     * @param buttonText
     */
    void execCheckParam(final CheckBox cb, final String buttonText) {
        resetCheckBoxStatus(cb, buttonText);
        BjdcHHDialog.SHOWTYPE type;
        if (pager == 1) {
            type = BjdcHHDialog.SHOWTYPE.SHOWBF;
        } else if (pager == 3) {
            type = BjdcHHDialog.SHOWTYPE.SHOWBQC;
        } else {
            type = BjdcHHDialog.SHOWTYPE.SHOWALL;
        }
        BjdcHHDialog dialog = new BjdcHHDialog(getContext(), this.mItem.getCodes(), this.mItem.getMap(), type);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {
                if (mItem.getMap() != null)
                    mItem.getMap().clear();
                mItem.setMap(map);
                String desc = mItem.getMapLength() > 0 ? "已选中" + mItem.getMapLength() + "项" : buttonText;
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                init();
                statistics();
            }
        });
        dialog.show();
    }

    void initSPF(List<String[]> strList) {
        //当前采种下面有几种比例选项 llspf 第一个是textview
        String[] strings;
        if(strList == null)
            strings = new String[]{"0","0","0"};
        else
            strings = strList.get(0);
        for (int i = 0; i < strings.length; i++) {
            CheckBox cb = (CheckBox) llspf.getChildAt(i + 1);
            cb.setOnClickListener(this);
            StringBuilder tag = new StringBuilder("0_spf_" + i + "_" + strings[i]);
            if (i == 1) {
                cb.setText(("平" + strings[i]));
                tag.append("_平");
            } else if (i == 0) {
                cb.setText(("胜" + strings[i]));
                tag.append("_胜");
            } else if (i == 2) {
                cb.setText(("负" + strings[i]));
                tag.append("_负");
            }
            tag.append("_");
            tag.append(spf[i]);
            cb.setTag(tag.toString());
            cb.setChecked(isCheckThisView(cb.getTag().toString(), "0"));
            saleTime(cb,"0".equals(strings[i]) || TextUtils.isEmpty(strings[i]));
        }
    }

    void initBQC() {
    }

    void initBF() {
    }

    void initDS(List<String[]> strList) {
        int childCount = ll_ds.getChildCount();
        int index = 0;
        String[] names = new String[]{"上单","上双","下单","下双"};
        String[] strs;
        if(strList == null)
            strs = new String[]{"0","0","0","0"};
        else
            strs = strList.get(1);
        //大小单双的值上单3 上双2 下单1 下双0
        for (int i=0;i<childCount;i++){
            ViewGroup childAt = (ViewGroup) ll_ds.getChildAt(i);
            for (int j=0;j<childAt.getChildCount();j++){
                CheckBox cb = (CheckBox) childAt.getChildAt(j);
                StringBuilder tag = new StringBuilder("3_sxp_" + index + "_" + strs[index] + "_" + names[index] + "_" + (3-index));
                cb.setOnClickListener(this);
                cb.setTag(tag.toString());
                StringBuilder sb = new StringBuilder();
                sb.append(names[index]);
                sb.append("<br/><small><small>");
                sb.append(strs[(3-index)]);
                sb.append("</small></small>");
                cb.setText(Html.fromHtml(sb.toString()));
                cb.setChecked(isCheckThisView(cb.getTag().toString(), "3"));
                saleTime(cb, "0".equals(codes[0]) || TextUtils.isEmpty(codes[0]) ||
                        "0".equals(strs[i]) || TextUtils.isEmpty(strs[i]));
                index++;
            }
        }
    }

    void initZJQ(List<String[]> strList) {
        //当前采种下面有几种比例选项
        String[] str0;
        if(strList == null)
            str0 = new String[]{"0","0","0","0","0","0","0","0"};
        else
            str0 = strList.get(2);
        int childCount = llAll.getChildCount();//混投布局是上下两个linearlayout 每个 linearlayout下四个子view
        int index = 0;
        for (int i = 0; i < childCount; i++) {
            ViewGroup child = (ViewGroup) llAll.getChildAt(i);
            for (int j = 0; j < child.getChildCount(); j++) {
                CheckBox cb = (CheckBox) child.getChildAt(j);
                StringBuilder tag = new StringBuilder("2_jqs_" + index + "_" + str0[index] + "_" + index + "_" + index);
                cb.setOnClickListener(this);
                StringBuilder sb = new StringBuilder();
                sb.append(index);
                if (i == childCount - 1 && j == child.getChildCount() - 1)
                    sb.append("球+");
                else
                    sb.append("球");
                sb.append("<br/><small><small>");
                sb.append(str0[index]);
                sb.append("</small></small>");
                cb.setText(Html.fromHtml(sb.toString()));
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), "2"));
                saleTime(cb, "0".equals(str0[index]) || TextUtils.isEmpty(str0[index]));
                index++;
            }
        }
    }

    void saleTime(CheckBox cb, boolean isNotSale) {
        cb.setEnabled(true);
        cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
        if (isNotSale) {
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
        }
    }

    @Override
    public void onClick(View v) {
        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        String tag = v.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
        statistics();
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.mItem.getMap() == null) return false;
        if (this.mItem.getMap().get(index) != null) {
            return this.mItem.getMap().get(index).get(tag) != null;
        }
        return false;
    }

    //统计勾选的数据
    private void statistics() {
        if (mItem.getMapLength() > 0) {
            if (!Utils.ZQ_ITEM_LIST.contains(mItem)) {
                if (mPosition < Utils.ZQ_ITEM_LIST.size())
                    Utils.ZQ_ITEM_LIST.add(mPosition, mItem);
                else
                    Utils.ZQ_ITEM_LIST.add(mItem);
            }
        } else {
            if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
                Utils.ZQ_ITEM_LIST.remove(mItem);
            }
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public void setChangeListener(Callback change) {
        this.changed = change;
    }
}
